package com.hxy.manager.service;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
import android.widget.Toast;

import com.alibaba.fastjson.JSONObject;
import com.ejlchina.okhttps.HttpResult;
import com.ejlchina.okhttps.OkHttps;
import com.ejlchina.okhttps.internal.AsyncHttpTask;
import com.hxy.manager.activity.goods.GoodsStoreActivity;
import com.hxy.manager.dao.DBManager;
import com.hxy.manager.entity.DaoMaster;
import com.hxy.manager.entity.DaoSession;
import com.hxy.manager.entity.GoodsEntity;
import com.hxy.manager.entity.GoodsEntityDao;
import com.hxy.manager.util.Constant;
import com.hxy.manager.util.StringUtil;
import com.hxy.manager.util.Tags;

import java.io.IOException;
import java.util.List;

/**
 * 商品添加的逻辑
 */
public class GoodsEntityService {

    private Context context;

    GoodsEntityService(Context context) {
        this.context = context;
    }

    /**
     * @param context
     * @param goodsEntity
     * @return 插入后的id
     */
    public static long save(Context context, GoodsEntity goodsEntity) {
        // 保存到本地并且同步到线上数据库
        DaoSession writeSession = DBManager.getWriteSession(context);
        GoodsEntityDao goodsEntityDao = writeSession.getGoodsEntityDao();
        long insert = goodsEntityDao.insert(goodsEntity);
        writeSession.clear();
        return insert;
    }

    /**
     * @param context
     * @param goodsEntity
     * @return 插入后的id
     */
    public static void saveBatch(Context context, GoodsEntity... goodsEntity) {
        // 保存到本地并且同步到线上数据库
        DaoSession writeSession = DBManager.getWriteSession(context);
        GoodsEntityDao goodsEntityDao = writeSession.getGoodsEntityDao();
        goodsEntityDao.insertInTx(goodsEntity);
        writeSession.clear();
    }

    /**
     * @param context
     * @param goodsEntity
     * @return 插入后的id
     */
    public static void saveBatch(Context context, List<GoodsEntity> goodsEntity) {

        // 保存到本地并且同步到线上数据库
        DaoSession writeSession = DBManager.getWriteSession(context);
        GoodsEntityDao goodsEntityDao = writeSession.getGoodsEntityDao();
        goodsEntityDao.insertInTx(goodsEntity);
        writeSession.clear();
    }

    public static void update(Context context, GoodsEntity goodsEntity) {
        DaoSession writeSession = DBManager.getWriteSession(context);
        GoodsEntityDao goodsEntityDao = writeSession.getGoodsEntityDao();
        goodsEntityDao.update(goodsEntity);
        writeSession.clear();

//        同步到线上服务器
        putToServer(context, goodsEntity);

    }

    @Deprecated
    public static void updateByNumber(Context context, GoodsEntity goodsEntity) {
        DaoSession writeSession = DBManager.getWriteSession(context);
        GoodsEntityDao goodsEntityDao = writeSession.getGoodsEntityDao();
//        goodsEntityDao.update();
    }

    public static void delete(Context context, GoodsEntity goodsEntity) {
        DaoSession writeSession = DBManager.getWriteSession(context);
        GoodsEntityDao goodsEntityDao = writeSession.getGoodsEntityDao();
        goodsEntityDao.delete(goodsEntity);
        writeSession.clear();

        deleteFromServer(context, goodsEntity);

    }


    public static List<GoodsEntity> listAll(Context context) {
        DaoMaster.DevOpenHelper devOpenHelper = new DaoMaster.DevOpenHelper(context, Constant.SQLITE_DATABASE, null);
        SQLiteDatabase readableDatabase = devOpenHelper.getReadableDatabase();
        DaoMaster daoMaster = new DaoMaster(readableDatabase);
        DaoSession daoSession = daoMaster.newSession();
        GoodsEntityDao goodsEntityDao = daoSession.getGoodsEntityDao();
        return goodsEntityDao.loadAll();
    }

    /**
     * 模糊搜索
     *
     * @return
     */
    public static List<GoodsEntity> getOneBySearch(Context context, String value) {
        DaoSession readSession = DBManager.getReadSession(context);
        GoodsEntityDao goodsEntityDao = readSession.getGoodsEntityDao();
        List<GoodsEntity> list = goodsEntityDao.queryBuilder().where(GoodsEntityDao.Properties.Name.like("%" + value + "%")).list();
        readSession.clear();
        return list;
    }

    public static GoodsEntity getOneByNumber(Context context, String number) {
        DaoSession readSession = DBManager.getReadSession(context);
        GoodsEntityDao goodsEntityDao = readSession.getGoodsEntityDao();
        GoodsEntity goodsEntity = goodsEntityDao.queryBuilder().where(GoodsEntityDao.Properties.Number.eq(number)).unique();
        readSession.clear();
        return goodsEntity;
    }

    /**
     * 获取我的信息
     **/
    public AsyncHttpTask updatePasswrod(String passwrod) {
        return OkHttps.async("/mine/passwrod")
                .bind(context)
                .tag(Tags.TOKEN)        // 自动添加 TOEKN
                .tag(Tags.LOADING)      // 自动显示加载框
                .addBodyPara("passwrod", passwrod);
    }


    public static HttpResult postToServer(Context context, GoodsEntity goodsEntity) {
        return OkHttps.async("/goods")
                .bind(context)             // 绑定（生命周期|Context获取）
//                            .tag(Tags.TOKEN)        // 自动添加 TOEKN
                .tag(Tags.LOADING)      // 自动显示加载框
                .setBodyPara(goodsEntity)
                .bodyType(OkHttps.JSON)
                .setOnResponse(res -> {
//                    editText4.setText(res.toString());
                })
                .setOnException((IOException e) -> {
                    // 这里处理请求异常
                    Log.i("kkk", "异步异常捕获：" + e.getMessage());
//                    editText4.setText(e.getMessage());
                })
                // 请求参数设置...
                .post().getResult();

    }

    public static HttpResult putToServer(Context context, GoodsEntity goodsEntity) {
        return OkHttps.async("/goods")
                .bind(context)             // 绑定（生命周期|Context获取）
//                            .tag(Tags.TOKEN)        // 自动添加 TOEKN
                .tag(Tags.LOADING)      // 自动显示加载框
                .setBodyPara(goodsEntity)
                .bodyType(OkHttps.JSON)
                .setOnResponse(res -> {
//                    editText4.setText(res.toString());
                })
                .setOnException((IOException e) -> {
                    // 这里处理请求异常
                    Log.i("kkk", "异步异常捕获：" + e.getMessage());
//                    editText4.setText(e.getMessage());
                })
                // 请求参数设置...
                .put().getResult();
    }


    public static HttpResult deleteFromServer(Context context, GoodsEntity goodsEntity) {
        return OkHttps.async("/goods")
                .bind(context)             // 绑定（生命周期|Context获取）
//                            .tag(Tags.TOKEN)        // 自动添加 TOEKN
                .tag(Tags.LOADING)      // 自动显示加载框
                .setBodyPara(goodsEntity)
                .bodyType(OkHttps.JSON)
                .setOnResponse(res -> {
//                    editText4.setText(res.toString());
                })
                .setOnException((IOException e) -> {
                    // 这里处理请求异常
                    Log.i("kkk", "异步异常捕获：" + e.getMessage());
//                    editText4.setText(e.getMessage());
                })
                // 请求参数设置...
                .delete().getResult();
    }

    /**
     * 把本地所有的全部上传
     *
     * @param goodsEntities
     * @return
     */
    public HttpResult postAllToServer(List<GoodsEntity> goodsEntities) {
        return OkHttps.async("/goods/list")
                .bind(context)             // 绑定（生命周期|Context获取）
//                            .tag(Tags.TOKEN)        // 自动添加 TOEKN
//                .tag(Tags.LOADING)      // 自动显示加载框
                .setBodyPara(goodsEntities)
                .bodyType(OkHttps.JSON)
                .setOnResponse(res -> {
//                    editText4.setText(res.toString());
                    Toast.makeText(GoodsStoreActivity.goodsStoreActivity, "同步到线上成功", Toast.LENGTH_SHORT).show();

                })
                .setOnException((IOException e) -> {
                    // 这里处理请求异常
                    Log.i("kkk", "异步异常捕获：" + e.getMessage());
                    Toast.makeText(GoodsStoreActivity.goodsStoreActivity, "服务不在线", Toast.LENGTH_SHORT).show();

//                    editText4.setText(e.getMessage());
                })
                // 请求参数设置...
                .post().getResult();
    }


    /**
     * 请求服务器下载数据
     *
     * @return
     */
    public String requestGetListAll() {
//         异步操作，多线程操作
        Object lock = new Object();

        HttpResult result = OkHttps.async("/goods/list")
                .bind(context)             // 绑定（生命周期|Context获取）
//                            .tag(Tags.TOKEN)        // 自动添加 TOEKN
//                .tag(Tags.LOADING)      // 自动显示加载框
//                .setBodyPara(goodsEntities)
                .bodyType(OkHttps.JSON)
                .setOnResponse(res -> {
                    synchronized (lock) {
                        HttpResult.Body body1 = res.getBody().cache();
                        String bodyStr = body1.toString();
                        JSONObject jsonObject = JSONObject.parseObject(bodyStr);
                        String message = jsonObject.getString("message");

                        Toast.makeText(GoodsStoreActivity.goodsStoreActivity, message, Toast.LENGTH_SHORT).show();
                    }

                })
                .setOnException((IOException e) -> {
                    // 这里处理请求异常
                    Log.i("kkk", "异步异常捕获：" + e.getMessage());
                    Toast.makeText(GoodsStoreActivity.goodsStoreActivity, "服务不在线", Toast.LENGTH_SHORT).show();
                })
                // 请求参数设置...
                .get().getResult();


        synchronized (lock) {
            HttpResult.Body body = result.getBody();
            if (body != null) {
                return body.cache().toString();
            }
        }
        return new String();
    }

    /**
     * 和服务器同步数据
     *
     * @return
     */
    public void syncData(Context context, List<GoodsEntity> goodsEntities) {
        if (goodsEntities != null && goodsEntities.size() > 0) {
            HttpResult httpResult = postAllToServer(goodsEntities);
        }

        String httpResult1 = requestGetListAll();
        if (StringUtil.hasText(httpResult1)) {
            JSONObject jsonObject = JSONObject.parseObject(httpResult1);
            String message = jsonObject.getString("message");
            String data = jsonObject.getString("data");

            List<GoodsEntity> goodsEntities1 = JSONObject.parseArray(data, GoodsEntity.class);
            //        查询是否存在
            if (goodsEntities1 != null) {
                goodsEntities1.forEach(goodsEntity1 -> {
                    GoodsEntity oneByNumber = getOneByNumber(context, goodsEntity1.getNumber());
                    if (oneByNumber == null) {
//                    防止id冲突
                        goodsEntity1.setId(null);
                        save(context, goodsEntity1);
                    }
                });
            }
        }

    }
}
